//
/**
 Mobikul_Magento2V3_App
 @Category Webkul
 @author Webkul <support@webkul.com>
 FileName: UIImageView+extensions.swift
 Copyright (c) 2010-2018 Webkul Software Private Limited (https://webkul.com)
 @license https://store.webkul.com/license.html ASL Licence
 @link https://store.webkul.com/license.html
 
 */

import Foundation
import Kingfisher
import UIKit

enum LoadingStyle {
    case noani // 默认无等待动画
    case image(imageData: Data) // 图片，支持动画
    case activity // 系统菊花
    /// ...
}

public extension UIImageView {
    /// 加载网络图片
    /// - Parameters:
    ///   - url: 图片地址
    ///   - dominantColor: 主题颜色
    ///   - placeholder: 站位图片
    ///   - needLoading: 是否需要加载状态
    
    @discardableResult
    internal func setImage(fromURL: String?,
                           dominantColor: String? = "",
                           dominantColor2: UIColor? = nil,
                           placeholder: UIImage? = nil,
                           needBlurRadius: CGFloat? = 0,
                           cornerRadius: CGFloat? = 0,
                           forceRefresh: Bool? = false,
                           forceTransition: Bool? = false,
                           keepCurrentImageWhileLoading: Bool? = false,
                           loadingStyle: LoadingStyle? = .noani,
                           progressBlock: DownloadProgressBlock? = nil,
                           resize: CGFloat? = 0,
                           cachePath: String? = "",
                           completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
    {
        let oldBackgroundColor = self.backgroundColor
        
        if let url = fromURL, url.count > 0 {
            if url.hasPrefix("http") {
                // 如果使用urlQueryAllowed，地址中原本就有%会再次转成%25，导致加载不了
                // 自定义需要转义的字符
                let customAllowedSet = NSCharacterSet(charactersIn: " !#`^<>@[]|").inverted
                let sourceUrl = fromURL?.addingPercentEncoding(withAllowedCharacters: customAllowedSet)
                if let urlString = sourceUrl, let url = URL(string: urlString) {
                    if let color = dominantColor, color.count > 0 {
                        self.backgroundColor = UIColor.hex(hexString: color)
                    }
                    
                    if dominantColor2 != nil {
                        self.backgroundColor = dominantColor2
                    }
                    
                    if let style = loadingStyle {
                        switch style {
                        case .noani:
                            self.kf.indicatorType = .none
                        case .image(let data):
                            /**
                             let path = Bundle.main.path(forResource: "myImage", ofType: "gif")!
                             let data = try! Data(contentsOf: URL(fileURLWithPath: path))
                             imageView.kf.indicatorType = .image(imageData: data)
                             */
                            self.kf.indicatorType = .image(imageData: data)
                        case .activity:
                            self.kf.indicatorType = .activity
                        }
                    }
                        
                    var optionsInfo = KingfisherOptionsInfo()
                    
                    // 创建你想要应用的处理器数组
                    var processors = [ImageProcessor]() // 提供了很多图片处理
                        
                    // 完全自定义图片加载效果
                    /**
                     let transition = ImageTransition.custom(duration: 0.5, options: UIView.AnimationOptions.curveEaseOut) { imageView, image in
                         
                     } completion: { completed in
                         
                     }
                     */
                        
                    optionsInfo.append(.transition(.fade(0.5)))
                    
                    if let force = forceTransition, force == true {
                        optionsInfo.append(.forceTransition)
                    }
                    
                    if let size = resize, size > 0 {
                        // 当有多个processor时这样写，我想要动态的，就用数组装，要不然后面设置blurRadius相当于覆盖了processor
                        // 1，一次性写完
//                        let processor = DownsamplingImageProcessor(size: self.bounds.size)
//                                     |> RoundCornerImageProcessor(cornerRadius: 20)
                        // 2，一个个累加
//                        processor.append(another: ImageProcessor)
                        
                        // 3，选择第三种，先数组保存，最后合并
                        
                        processors.append(DownsamplingImageProcessor(size: CGSize(width: size, height: size)))
                        
                        optionsInfo.append(.scaleFactor(UIScreen.main.scale))
                        optionsInfo.append(.cacheOriginalImage)
                        
                        // transition滑动会很卡
                    }
                    
                    optionsInfo.append(.cacheOriginalImage)
                    
                    if let radius = needBlurRadius, radius > 0 {
                        processors.append(BlurImageProcessor(blurRadius: radius))
                    }
                    
                    if let radius = cornerRadius, radius > 0 {
                        processors.append(RoundCornerImageProcessor(cornerRadius: radius))
                    }
                        
                    if let force = forceRefresh, force == true {
                        optionsInfo.append(.forceRefresh)
                    }
                    
                    //切换首页壁纸时最好使用这个,避免出现白屏
                    if let keep = keepCurrentImageWhileLoading, keep == true {
                        optionsInfo.append(.keepCurrentImageWhileLoading)
                    }

                    
                    //自定义了缓存路径
                    if let cachep = cachePath, cachep.count > 0 {
                        
                        //默认的是ImageCache(name: "default")
                        let customCache = ImageCache(name: cachep)
                        optionsInfo.append(.targetCache(customCache))
                    }
                    
                    // 合并处理器
                    if processors.count > 0 {
                        let allprocessors = processors.reduce(processors[0]) { $0.append(another: $1) }
                        optionsInfo.append(.processor(allprocessors))
                    }
                    
                    // 指定一个cacheKey缓存图片,默认的cacheKey = url
                    // let resource = ImageResource(downloadURL: url, cacheKey: urlString)
                        
                    return self.kf.setImage(with: url, placeholder: placeholder, options: optionsInfo) { receivedSize, totalSize in
                            
                        if let prog = progressBlock {
                            prog(receivedSize, totalSize)
                        }
                            
                        // 自定义加载进度
                        // let progress = Double(receivedSize) / Double(totalSize)
                            
                    } completionHandler: { result in
                            
                        self.backgroundColor = oldBackgroundColor
                        // 加载完图片，自定义一些处理
                            
                        if let comp = completionHandler {
                            comp(result)
                        }
                            
                        /**
                         switch result {
                         case .success(let value):
                         SJCLog(value.cacheType,value.source)
                         case .failure(let error):
                         SJCLog(error)
                         }
                         */
                    }
                        
                } else {
                    if let place = placeholder {
                        self.image = place
                    } else {
                        // 这句很重要，不写，cell的复用会导致图像不设置而错乱
                        self.image = nil
                    }
                }
                
            } else {
                self.image = UIImage(named: url)
            }
        } else {
            if let place = placeholder {
                self.image = place
            } else {
                // 这句很重要，不写，cell的复用会导致图像不设置而错乱
                self.image = nil
            }
        }
        return nil
    }
    
   
}
